package com.gkj.blog.framework.object;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.ParameterizedType;
import java.util.Date;

public abstract class AbstractServiceImpl<VO extends BaseEntityVo,PO extends AbstractDO> implements AbstractService<VO> {
    private static final Logger logger= LoggerFactory.getLogger(AbstractServiceImpl.class);

    public BaseMapper baseMapper;
    Class<VO> voClass;
    Class<PO> poClass;
    Constructor voConstructor;

    public AbstractServiceImpl(){
        //获取泛型值
        ParameterizedType pt =  (ParameterizedType)this.getClass().getGenericSuperclass();
        voClass = (Class<VO>)pt.getActualTypeArguments()[0];
        poClass = (Class<PO>)pt.getActualTypeArguments()[1];
        try {
            voConstructor=voClass.getDeclaredConstructor(new Class[]{poClass});
        } catch (NoSuchMethodException e) {
            logger.error("没有找指定的构造方法---{}",e.toString());
        }
    }
    public void setBaseMapper(BaseMapper baseMapper){
        this.baseMapper=baseMapper;
    };

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(Long id) {
        return baseMapper.deleteByPrimaryKey(id)>0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteIds(Long[] ids) {
        if(ids==null||ids.length==0){
            return false;
        }
        for(Long id:ids){
            baseMapper.deleteByPrimaryKey(id);
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public VO insert(VO record) {

        Assert.notNull(record,record.getClass().getSimpleName()+"不能为空");
        record.setCreateTime(new Date());
        record.setUpdateTime(new Date());
        baseMapper.insertSelective(record.getAbstractDo());
        return record;
    }

    @Override
    public VO select(Long id) {
        Assert.notNull(id, "id不可为空！");
        VO vo=null;
        try {
            vo = (VO) voConstructor.newInstance(baseMapper.selectByPrimaryKey(id));
        } catch (Exception e) {
            logger.error("构造{}实例化失败:{}",poClass.getSimpleName(),e.toString());
        }
        return vo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean update(VO record) {
        Assert.notNull(record,"Tags不能为空");
        record.setUpdateTime(new Date());
        return baseMapper.updateByPrimaryKeySelective(record.getAbstractDo())>0;
    }
}
